//
//  BirthdayViewController.m
//  CangLongWnnianli
//
//  Created by 暗流澎涌 on 2025/1/27.
//

#import "BirthdayViewController.h"
#import "AddBirthdayViewController.h"
#import "BirthdayDetailViewController.h"

@interface BirthdayViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *emptyView;

@end

@implementation BirthdayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadBirthdayData];
    [self updateEmptyView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"BirthdayViewController viewWillAppear - 开始刷新数据");
    [self loadBirthdayData];
    [self.tableView reloadData];
    [self updateEmptyView];
    NSLog(@"BirthdayViewController viewWillAppear - 数据刷新完成，当前列表数量: %lu", (unsigned long)self.birthdayList.count);
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.0];
    self.title = @"农历生日提醒";
    
    // 创建TableView
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    
    // 创建添加按钮
    self.addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.addButton setImage:[UIImage systemImageNamed:@"plus"] forState:UIControlStateNormal];
    self.addButton.backgroundColor = [UIColor colorWithRed:0.4 green:0.6 blue:1.0 alpha:1.0];
    self.addButton.layer.cornerRadius = 28;
    self.addButton.layer.shadowColor = [UIColor blackColor].CGColor;
    self.addButton.layer.shadowOffset = CGSizeMake(0, 4);
    self.addButton.layer.shadowOpacity = 0.3;
    self.addButton.layer.shadowRadius = 8;
    [self.addButton addTarget:self action:@selector(addBirthdayButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.addButton];
    

    
    // 创建空状态视图
    [self setupEmptyView];
    
    // 设置约束
    [self setupConstraints];
}

- (void)setupEmptyView {
    self.emptyView = [[UIView alloc] init];
    self.emptyView.hidden = YES;
    [self.view addSubview:self.emptyView];
    
    UIImageView *iconView = [[UIImageView alloc] init];
    iconView.image = [UIImage systemImageNamed:@"birthday.cake"];
    iconView.tintColor = [UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:1.0];
    iconView.contentMode = UIViewContentModeScaleAspectFit;
    [self.emptyView addSubview:iconView];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"还没有生日提醒";
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    titleLabel.textColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.emptyView addSubview:titleLabel];
    
    UILabel *subtitleLabel = [[UILabel alloc] init];
    subtitleLabel.text = @"添加亲朋好友的农历生日，不错过每一个重要时刻";
    subtitleLabel.font = [UIFont systemFontOfSize:14];
    subtitleLabel.textColor = [UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:1.0];
    subtitleLabel.textAlignment = NSTextAlignmentCenter;
    subtitleLabel.numberOfLines = 0;
    [self.emptyView addSubview:subtitleLabel];
    
    UIButton *addFirstButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [addFirstButton setTitle:@"添加第一个生日提醒" forState:UIControlStateNormal];
    [addFirstButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addFirstButton.backgroundColor = [UIColor colorWithRed:0.4 green:0.6 blue:1.0 alpha:1.0];
    addFirstButton.layer.cornerRadius = 12;
    addFirstButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [addFirstButton addTarget:self action:@selector(addBirthdayButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.emptyView addSubview:addFirstButton];
    
    // 设置空状态视图约束
    iconView.translatesAutoresizingMaskIntoConstraints = NO;
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    subtitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    addFirstButton.translatesAutoresizingMaskIntoConstraints = NO;
    
    [NSLayoutConstraint activateConstraints:@[
        [iconView.centerXAnchor constraintEqualToAnchor:self.emptyView.centerXAnchor],
        [iconView.centerYAnchor constraintEqualToAnchor:self.emptyView.centerYAnchor constant:-60],
        [iconView.widthAnchor constraintEqualToConstant:80],
        [iconView.heightAnchor constraintEqualToConstant:80],
        
        [titleLabel.topAnchor constraintEqualToAnchor:iconView.bottomAnchor constant:20],
        [titleLabel.leadingAnchor constraintEqualToAnchor:self.emptyView.leadingAnchor constant:20],
        [titleLabel.trailingAnchor constraintEqualToAnchor:self.emptyView.trailingAnchor constant:-20],
        
        [subtitleLabel.topAnchor constraintEqualToAnchor:titleLabel.bottomAnchor constant:10],
        [subtitleLabel.leadingAnchor constraintEqualToAnchor:self.emptyView.leadingAnchor constant:40],
        [subtitleLabel.trailingAnchor constraintEqualToAnchor:self.emptyView.trailingAnchor constant:-40],
        
        [addFirstButton.topAnchor constraintEqualToAnchor:subtitleLabel.bottomAnchor constant:30],
        [addFirstButton.centerXAnchor constraintEqualToAnchor:self.emptyView.centerXAnchor],
        [addFirstButton.widthAnchor constraintEqualToConstant:200],
        [addFirstButton.heightAnchor constraintEqualToConstant:44]
    ]];
}

- (void)setupConstraints {
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    self.addButton.translatesAutoresizingMaskIntoConstraints = NO;
    self.emptyView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [NSLayoutConstraint activateConstraints:@[
        [self.tableView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.tableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
        
        [self.addButton.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-20],
        [self.addButton.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor constant:-100],
        [self.addButton.widthAnchor constraintEqualToConstant:56],
        [self.addButton.heightAnchor constraintEqualToConstant:56],
        
        [self.emptyView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [self.emptyView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.emptyView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.emptyView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor]
    ]];
}

- (void)loadBirthdayData {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *savedData = [defaults objectForKey:@"BirthdayList"];
    
    self.birthdayList = [NSMutableArray array];
    
    if (savedData) {
        NSLog(@"加载到 %lu 条生日数据", (unsigned long)savedData.count);
        for (NSDictionary *dict in savedData) {
            NSLog(@"原始数据: %@", dict);
            BirthdayModel *model = [BirthdayModel fromDictionary:dict];
            [self.birthdayList addObject:model];
            NSLog(@"加载生日数据: %@ - 农历%@%@ (月:%ld, 日:%ld)", model.name, [model lunarMonthName], [model lunarDayName], (long)model.lunarMonth, (long)model.lunarDay);
        }
    } else {
        NSLog(@"没有找到保存的生日数据");
    }
    
    // 按距离生日的天数排序
    [self.birthdayList sortUsingComparator:^NSComparisonResult(BirthdayModel *obj1, BirthdayModel *obj2) {
        return [@([obj1 daysUntilBirthday]) compare:@([obj2 daysUntilBirthday])];
    }];
    
    NSLog(@"当前生日列表数量: %lu", (unsigned long)self.birthdayList.count);
}

- (void)saveBirthdayData {
    NSMutableArray *dataArray = [NSMutableArray array];
    for (BirthdayModel *model in self.birthdayList) {
        [dataArray addObject:[model toDictionary]];
    }
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:dataArray forKey:@"BirthdayList"];
    [defaults synchronize];
    
    NSLog(@"保存了 %lu 条生日数据", (unsigned long)dataArray.count);
}

- (void)updateEmptyView {
    self.emptyView.hidden = self.birthdayList.count > 0;
    self.addButton.hidden = self.birthdayList.count == 0;
}

- (void)addBirthdayButtonTapped {
    AddBirthdayViewController *addVC = [[AddBirthdayViewController alloc] init];
    addVC.completionBlock = ^(BirthdayModel *birthday) {
        NSLog(@"添加新生日: %@ - 农历%@%@", birthday.name, [birthday lunarMonthName], [birthday lunarDayName]);
        [self.birthdayList addObject:birthday];
        [self saveBirthdayData];
        [self.tableView reloadData];
        [self updateEmptyView];
        NSLog(@"添加完成后，当前列表数量: %lu", (unsigned long)self.birthdayList.count);
    };
    
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:addVC];
    navController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:navController animated:YES completion:nil];
}



#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSLog(@"TableView numberOfRowsInSection: %lu", (unsigned long)self.birthdayList.count);
    return self.birthdayList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"BirthdayCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        // 创建生日卡片视图
        UIView *cardView = [[UIView alloc] init];
        cardView.layer.cornerRadius = 16;
        cardView.layer.shadowColor = [UIColor blackColor].CGColor;
        cardView.layer.shadowOffset = CGSizeMake(0, 2);
        cardView.layer.shadowOpacity = 0.1;
        cardView.layer.shadowRadius = 8;
        cardView.tag = 100;
        
        // 创建渐变层容器
        UIView *gradientContainer = [[UIView alloc] init];
        gradientContainer.tag = 106;
        gradientContainer.layer.cornerRadius = 16;
        [cardView addSubview:gradientContainer];
        
        [cell.contentView addSubview:cardView];
        
        // 姓名标签
        UILabel *nameLabel = [[UILabel alloc] init];
        nameLabel.font = [UIFont boldSystemFontOfSize:18];
        nameLabel.textColor = [UIColor whiteColor];
        nameLabel.tag = 101;
        [cardView addSubview:nameLabel];
        
        // 农历日期标签
        UILabel *lunarLabel = [[UILabel alloc] init];
        lunarLabel.font = [UIFont systemFontOfSize:14];
        lunarLabel.textColor = [UIColor whiteColor];
        lunarLabel.alpha = 0.9;
        lunarLabel.tag = 102;
        [cardView addSubview:lunarLabel];
        
        // 倒计时标签
        UILabel *countdownLabel = [[UILabel alloc] init];
        countdownLabel.font = [UIFont systemFontOfSize:14];
        countdownLabel.textColor = [UIColor whiteColor];
        countdownLabel.alpha = 0.9;
        countdownLabel.tag = 103;
        [cardView addSubview:countdownLabel];
        
        // 状态标签
        UILabel *statusLabel = [[UILabel alloc] init];
        statusLabel.font = [UIFont systemFontOfSize:12];
        statusLabel.textColor = [UIColor whiteColor];
        statusLabel.alpha = 0.75;
        statusLabel.textAlignment = NSTextAlignmentRight;
        statusLabel.tag = 104;
        [cardView addSubview:statusLabel];
        
        // 表情图标
        UILabel *emojiLabel = [[UILabel alloc] init];
        emojiLabel.font = [UIFont systemFontOfSize:24];
        emojiLabel.textAlignment = NSTextAlignmentRight;
        emojiLabel.tag = 105;
        [cardView addSubview:emojiLabel];
        
        // 设置约束
        cardView.translatesAutoresizingMaskIntoConstraints = NO;
        gradientContainer.translatesAutoresizingMaskIntoConstraints = NO;
        nameLabel.translatesAutoresizingMaskIntoConstraints = NO;
        lunarLabel.translatesAutoresizingMaskIntoConstraints = NO;
        countdownLabel.translatesAutoresizingMaskIntoConstraints = NO;
        statusLabel.translatesAutoresizingMaskIntoConstraints = NO;
        emojiLabel.translatesAutoresizingMaskIntoConstraints = NO;
        
        [NSLayoutConstraint activateConstraints:@[
            [cardView.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor constant:8],
            [cardView.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:16],
            [cardView.trailingAnchor constraintEqualToAnchor:cell.contentView.trailingAnchor constant:-16],
            [cardView.bottomAnchor constraintEqualToAnchor:cell.contentView.bottomAnchor constant:-8],
            
            [gradientContainer.topAnchor constraintEqualToAnchor:cardView.topAnchor],
            [gradientContainer.leadingAnchor constraintEqualToAnchor:cardView.leadingAnchor],
            [gradientContainer.trailingAnchor constraintEqualToAnchor:cardView.trailingAnchor],
            [gradientContainer.bottomAnchor constraintEqualToAnchor:cardView.bottomAnchor],
            
            [nameLabel.topAnchor constraintEqualToAnchor:cardView.topAnchor constant:20],
            [nameLabel.leadingAnchor constraintEqualToAnchor:cardView.leadingAnchor constant:20],
            [nameLabel.trailingAnchor constraintEqualToAnchor:emojiLabel.leadingAnchor constant:-10],
            
            [lunarLabel.topAnchor constraintEqualToAnchor:nameLabel.bottomAnchor constant:8],
            [lunarLabel.leadingAnchor constraintEqualToAnchor:cardView.leadingAnchor constant:20],
            
            [countdownLabel.topAnchor constraintEqualToAnchor:lunarLabel.bottomAnchor constant:4],
            [countdownLabel.leadingAnchor constraintEqualToAnchor:cardView.leadingAnchor constant:20],
            [countdownLabel.bottomAnchor constraintEqualToAnchor:cardView.bottomAnchor constant:-20],
            
            [emojiLabel.topAnchor constraintEqualToAnchor:cardView.topAnchor constant:20],
            [emojiLabel.trailingAnchor constraintEqualToAnchor:cardView.trailingAnchor constant:-20],
            [emojiLabel.widthAnchor constraintEqualToConstant:40],
            [emojiLabel.heightAnchor constraintEqualToConstant:40],
            
            [statusLabel.topAnchor constraintEqualToAnchor:emojiLabel.bottomAnchor constant:8],
            [statusLabel.trailingAnchor constraintEqualToAnchor:cardView.trailingAnchor constant:-20],
            [statusLabel.bottomAnchor constraintEqualToAnchor:cardView.bottomAnchor constant:-20]
        ]];
    }
    
    BirthdayModel *birthday = self.birthdayList[indexPath.row];
    NSLog(@"配置第 %ld 行: %@ - 农历%@%@ (月:%ld, 日:%ld)", (long)indexPath.row, birthday.name, [birthday lunarMonthName], [birthday lunarDayName], (long)birthday.lunarMonth, (long)birthday.lunarDay);
    
    UIView *cardView = [cell.contentView viewWithTag:100];
    UIView *gradientContainer = [cell.contentView viewWithTag:106];
    UILabel *nameLabel = [cell.contentView viewWithTag:101];
    UILabel *lunarLabel = [cell.contentView viewWithTag:102];
    UILabel *countdownLabel = [cell.contentView viewWithTag:103];
    UILabel *statusLabel = [cell.contentView viewWithTag:104];
    UILabel *emojiLabel = [cell.contentView viewWithTag:105];
    
    nameLabel.text = birthday.name;
    lunarLabel.text = [NSString stringWithFormat:@"农历%@%@", [birthday lunarMonthName], [birthday lunarDayName]];
    
    NSInteger days = [birthday daysUntilBirthday];
    if (days == 0) {
        countdownLabel.text = @"今天就是生日！";
        emojiLabel.text = @"🎂";
    } else {
        countdownLabel.text = [NSString stringWithFormat:@"还有 %ld 天", (long)days];
        emojiLabel.text = @"🎉";
    }
    
    statusLabel.text = birthday.isEnabled ? @"已开启提醒" : @"已关闭提醒";
    

    
    // 设置渐变背景
    // 清除之前的渐变层
    for (CALayer *layer in gradientContainer.layer.sublayers) {
        [layer removeFromSuperlayer];
    }
    
    // 创建新的渐变层
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = gradientContainer.bounds;
    
    NSArray *colors = @[
        [UIColor colorWithRed:0.4 green:0.6 blue:1.0 alpha:1.0],
        [UIColor colorWithRed:0.6 green:0.4 blue:1.0 alpha:1.0]
    ];
    
    if (indexPath.row % 3 == 1) {
        colors = @[
            [UIColor colorWithRed:0.9 green:0.4 blue:0.6 alpha:1.0],
            [UIColor colorWithRed:0.9 green:0.6 blue:0.4 alpha:1.0]
        ];
    } else if (indexPath.row % 3 == 2) {
        colors = @[
            [UIColor colorWithRed:0.3 green:0.8 blue:1.0 alpha:1.0],
            [UIColor colorWithRed:0.0 green:0.9 blue:1.0 alpha:1.0]
        ];
    }
    
    gradientLayer.colors = @[
        (id)[colors[0] CGColor],
        (id)[colors[1] CGColor]
    ];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1, 1);
    
    [gradientContainer.layer insertSublayer:gradientLayer atIndex:0];
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BirthdayModel *birthday = self.birthdayList[indexPath.row];
    BirthdayDetailViewController *detailVC = [[BirthdayDetailViewController alloc] init];
    detailVC.birthday = birthday;
    detailVC.completionBlock = ^(BirthdayModel *updatedBirthday) {
        [self.birthdayList replaceObjectAtIndex:indexPath.row withObject:updatedBirthday];
        [self saveBirthdayData];
        [self.tableView reloadData];
    };
    detailVC.deleteBlock = ^{
        [self.birthdayList removeObjectAtIndex:indexPath.row];
        [self saveBirthdayData];
        [self.tableView reloadData];
        [self updateEmptyView];
    };
    
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:detailVC];
    navController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:navController animated:YES completion:nil];
}

@end 